﻿using STTech.BytesIO.Core;
using STTech.BytesIO.Core.Component;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace updTest
{
    public class BytesIO_UDPClientService
    {

        private STTech.BytesIO.Udp.UdpClient client;
        public void CreateService()
        {
            client = new STTech.BytesIO.Udp.UdpClient();
            client.Host = "224.100.0.1";
            client.Port = 11000;
            client.OnConnectedSuccessfully += Client_OnConnectedSuccessfully;
            client.Connect();
            client.OnDataReceived += Client_OnDataReceived;
            client.OnDisconnected += Client_OnDisconnected;
            client.OnExceptionOccurs += Client_Exceptioned;
           // Bytes_TerminatorReceiveFilter myDataPacker = new Bytes_TerminatorReceiveFilter();
           // myDataPacker.OnDataParsed += Data_Parse;
            //client.BindUnpacker(myDataPacker);
        }

        public void  CloseService()
        {
            if (client != null)
            {
                client.OnDataReceived -= Client_OnDataReceived;
                client.OnDisconnected -= Client_OnDisconnected;
                client.OnExceptionOccurs -= Client_Exceptioned;
                client.Dispose();
            }
        }

        private void Client_Exceptioned(object sender, ExceptionOccursEventArgs e)
        {
            Console.WriteLine("Exception");
            
        }
        private void Client_OnConnectedSuccessfully(object sender, ConnectedSuccessfullyEventArgs e)
        {
           // Console.WriteLine("connected  server success11");
            //SendData("hello server");
            
        }
        private void Client_OnDataReceived(object sender, DataReceivedEventArgs e)
        {
            byte[] bytes = e.Data;
            Console.WriteLine(bytes);
           // string keys = ConverUtility.BytesToString(bytes);
        }
        
        private void Client_OnDisconnected(object sender, DisconnectedEventArgs e)
        {
            Console.WriteLine("ConnectedDisconnected");
        }

        public void  SendData(byte[] data)
        {
            client.Send(data);
        }

        public  void SendData(string data)
        {
            //byte[] bytes = ConverUtility.StringToBytes(data);
            //SendData(bytes);
        }
    }
}
